 
/*
 * @Author: ZhouNan
 * @Date: 2022-04-11 20:53:39
 * @LastEditors: ZhouNan
 * @LastEditTime: 2022-04-21 20:37:43
 * @FilePath: \export_ts\src\config.ts
 * @Description: 
 */
import { existsSync, readFileSync, writeFileSync } from 'fs';
import * as CONST from './const';
import util from './util';

type ExportConfigStruct = {
    export_flag: string,
    export_property: boolean,
    bind_comp: boolean,
    comp_flags: CompFlagStruct[],
}

type CompFlagStruct = {
    key: string,
    value: string
}

let comp_flags_back: CompFlagStruct[] = [];

function getExportConfig(): ExportConfigStruct {
    let config: ExportConfigStruct;
    if (existsSync(CONST.EXPORT_CONFIG_PATH)) {
        let file = readFileSync(CONST.EXPORT_CONFIG_PATH, {encoding: 'utf-8'});
        config = JSON.parse(file);
    }
    else {
        config = {
            export_flag: '$',
            export_property: false,
            bind_comp: true,
            comp_flags: [],
        }
    }
    if (comp_flags_back.length == 0) {
        comp_flags_back = util.clone(config.comp_flags);
    } else {
        config.comp_flags = util.clone(comp_flags_back);
    }
    return config;
}

function saveCompFlagsConfig(data: CompFlagStruct[]) {
    let canSave = [];
    for (let i = 0; i < data.length; i++) {
        let d = data[i];
        if (d.key !== '' && d.value.trim() !== '') {
            canSave.push(d);
        }
    }
    comp_flags_back = util.clone(canSave);
}

function saveExportConfig(data: ExportConfigStruct) {
    let c: ExportConfigStruct= util.clone(data);
    c.comp_flags = comp_flags_back;
    writeFileSync(CONST.EXPORT_CONFIG_PATH, JSON.stringify(c));
}

function getCompoentStrConfig() {
    let file = readFileSync(CONST.COMP_STR_CONF_PATH, {encoding: 'utf-8'});
    if (file) {
        return JSON.parse(file);
    }
    return [];
}

export default {
    getExportConfig,
    saveCompFlagsConfig,
    getCompoentStrConfig,
    saveExportConfig,
}